package com.sd365.permission.centre.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.sd365.common.core.annotation.stuffer.CommonFieldStuffer;
import com.sd365.common.core.annotation.stuffer.MethodTypeEnum;
import com.sd365.common.core.common.aop.MyPageInfo;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BusinessErrorCode;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.util.BeanException;
import com.sd365.common.util.BeanUtil;
import com.sd365.permission.centre.dao.mapper.SubSystemMapper;
import com.sd365.permission.centre.entity.Company;
import com.sd365.permission.centre.entity.Organization;
import com.sd365.permission.centre.entity.SubSystem;
import com.sd365.permission.centre.entity.Tenant;
import com.sd365.permission.centre.pojo.dto.CompanyDTO;
import com.sd365.permission.centre.pojo.dto.OrganizationDTO;
import com.sd365.permission.centre.pojo.dto.SubSystemDTO;
import com.sd365.permission.centre.pojo.dto.TenantDTO;
import com.sd365.permission.centre.pojo.query.SubSystemQuery;
import com.sd365.permission.centre.service.SubSystemService;
import com.sd365.permission.centre.service.exception.UserCentreExceptionCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.validation.Valid;
import java.util.List;

@Service
public class SubSystemServiceImpl extends AbstractBaseDataServiceImpl implements SubSystemService {

    @Autowired
    private SubSystemMapper subSystemMapper;

    @Override
    @CommonFieldStuffer(methodType = MethodTypeEnum.ADD)
    public Boolean add(@Valid SubSystemDTO subSystemDTO) {
        SubSystem subSystem = BeanUtil.copy(subSystemDTO, SubSystem.class);
        super.baseDataStuff4Add(subSystem);
        return subSystemMapper.insert(subSystem) > 0;
    }

    @Override
    @CommonFieldStuffer(methodType = MethodTypeEnum.DELETE)
    public Boolean remove(Long id, Long version) {
        Example example = new Example(SubSystem.class);
        example.createCriteria().andEqualTo("id", id).andEqualTo("version", version);
        return subSystemMapper.deleteByExample(example) > 0;
    }

    @Override
    @Transactional
    @CommonFieldStuffer(methodType = MethodTypeEnum.DELETE)
    public Boolean batchDelete(SubSystemDTO[] subSystemDTOS) {
        if (subSystemDTOS.length == 0) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("批量删除参数不可以为空"));
        }
        for (SubSystemDTO subSystemDTO : subSystemDTOS) {
            Example example = new Example(SubSystem.class);
            example.createCriteria().andEqualTo("id", subSystemDTO.getId()).andEqualTo("version", subSystemDTO.getVersion());
            int result = subSystemMapper.deleteByExample(example);
//                boolean result = remove(notifyRecordDTO.getId(), notifyRecordDTO.getVersion());
            if (result <= 0) {
                throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("删除的" + subSystemDTO.getId() + "记录有匹配到版本"));
            }
        }
        return true;
    }

    @Override
    @CommonFieldStuffer(methodType = MethodTypeEnum.UPDATE)
    public SubSystemDTO modify(SubSystemDTO subSystemDTO) {
        SubSystem subSystem = BeanUtil.copy(subSystemDTO, SubSystem.class);

        Long version = subSystemDTO.getVersion();
        version++;
        subSystem.setVersion(version);
        super.baseDataStuff4Updated(subSystem);
        if (subSystemMapper.updateSubSystem(subSystem) > 0) {
            SubSystemDTO subSystemDTOEdit = null;
            SubSystem subSystemEdit = subSystemMapper.selectById(subSystemDTO.getId());
            if (subSystemEdit != null) {
                subSystemDTOEdit = BeanUtil.copy(subSystemEdit, SubSystemDTO.class);
                BeanUtil.copy(subSystemEdit.getCompany(), subSystemDTOEdit.getCompany(), Company.class);
                BeanUtil.copy(subSystemEdit.getOrganization(), subSystemDTOEdit.getOrganization(), Organization.class);
                BeanUtil.copy(subSystemEdit.getTenant(), subSystemDTOEdit.getTenant(), Tenant.class);
            }
            return subSystemDTOEdit;
        } else {
            return null;
        }
    }

    @Override
    @CommonFieldStuffer(methodType = MethodTypeEnum.QUERY)
    public List<SubSystemDTO> commonQuery(SubSystemQuery subSystemQuery) {
        if (subSystemQuery == null) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("commonQuery 方法错误"));
        }
        try {
            SubSystem subSystem = new SubSystem();
            subSystem.setName(subSystemQuery.getName());
            subSystem.setCode(subSystemQuery.getCode());
            subSystem.setImageUrl(subSystemQuery.getImageUrl());
            subSystem.setRemark(subSystemQuery.getRemark());
            List<SubSystem> subSystems = subSystemMapper.commonQuery(subSystem);
            //对象转化 po list to dto list
            Page page = (Page) subSystems;
            BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(), page.getPages())));
            List<SubSystemDTO> notifyRecordDTOS = BeanUtil.copyList(subSystems, SubSystemDTO.class, new BeanUtil.CopyCallback() {
                @Override
                public void copy(Object o, Object o1) {
                    // 调用 BeanUtil.copyProperties
                    if (o == null || o1 == null) {
                        throw new BeanException("拷贝对象不可以为空", new Exception("copyList 拷贝回调错误"));
                    }

                    SubSystem notifyRecordSource = (SubSystem) o;
                    SubSystemDTO notifyRecordDTO = (SubSystemDTO) o1;
                    BeanUtil.copy(notifyRecordSource.getCompany(), notifyRecordDTO.getCompany(), Company.class);
                    BeanUtil.copy(notifyRecordSource.getOrganization(), notifyRecordDTO.getOrganization(), Organization.class);
                    BeanUtil.copy(notifyRecordSource.getTenant(), notifyRecordDTO.getTenant(), Tenant.class);
                }
            });
            return notifyRecordDTOS;
        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_TMS_MONITOR_MOTIFY_RECORD_DB_EXCEPTION_CODE, ex);

        }
    }

    @Override
    @CommonFieldStuffer(methodType = MethodTypeEnum.QUERY)
    public SubSystemDTO querySubSystemById(Long id) {
        try {
            SubSystemDTO subSystemDTO = null;
            SubSystem subSystem = subSystemMapper.selectById(id);
            if (subSystem != null) {
                subSystemDTO = BeanUtil.copy(subSystem, SubSystemDTO.class);
                BeanUtil.copy(subSystem.getCompany(), subSystemDTO.getCompany(), Company.class);
                BeanUtil.copy(subSystem.getOrganization(), subSystemDTO.getOrganization(), Organization.class);
                BeanUtil.copy(subSystem.getTenant(), subSystemDTO.getTenant(), Tenant.class);
            }
            return subSystemDTO;
        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_TMS_MONITOR_MOTIFY_RECORD_DB_EXCEPTION_CODE, ex);
        }
    }

    @Override
    public List<SubSystemDTO> querySubSystemByTenantId(Long id) {
        try {
            SubSystemDTO subSystemDTO = null;
            List<SubSystem> subSystems = subSystemMapper.selectByTenantId(id);
            List<SubSystemDTO> notifyRecordDTOS = BeanUtil.copyList(subSystems, SubSystemDTO.class, new BeanUtil.CopyCallback() {
                @Override
                public void copy(Object o, Object o1) {
                    // 调用 BeanUtil.copyProperties
                    if (o == null || o1 == null) {
                        throw new BeanException("拷贝对象不可以为空", new Exception("copyList 拷贝回调错误"));
                    }

                    SubSystem notifyRecordSource = (SubSystem) o;
                    SubSystemDTO notifyRecordDTO = (SubSystemDTO) o1;
                    BeanUtil.copy(notifyRecordSource.getCompany(), notifyRecordDTO.getCompany(), CompanyDTO.class);
                    BeanUtil.copy(notifyRecordSource.getOrganization(), notifyRecordDTO.getOrganization(), OrganizationDTO.class);
                    BeanUtil.copy(notifyRecordSource.getTenant(), notifyRecordDTO.getTenant(), TenantDTO.class);
                }
            });
            return notifyRecordDTOS;
//            SubSystem subSystem= subSystemMapper.selectByTenantId(id);
//            if(subSystem!=null) {
//                subSystemDTO = BeanUtil.copy(subSystem, SubSystemDTO.class);
//                BeanUtil.copy(subSystem.getCompany(),subSystemDTO.getCompany(), Company.class);
//                BeanUtil.copy(subSystem.getOrganization(),subSystemDTO.getOrganization(), Organization.class);
//                BeanUtil.copy(subSystem.getTenant(),subSystemDTO.getTenant(), Tenant.class);
//            }
//            return subSystemDTO;
        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_TMS_MONITOR_MOTIFY_RECORD_DB_EXCEPTION_CODE, ex);
        }
    }

    @Override
    public List<Tenant> tenantQuery() {
        try {
            List<Tenant> tenants = subSystemMapper.tenantQuery();
            return tenants;
        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_TMS_MONITOR_MOTIFY_RECORD_DB_EXCEPTION_CODE, ex);
        }
    }
}
